const express = require("express");
const router = express.Router();
const verifyToken = require("../utils/verifyToken");
const sqlconfig = require("../mysql/config");
const {
  createResponse
} = require("../utils/responseHelper");
const {
  sendToUser,
  sendToAdmins
} = require("../websocket");
const {
  formatDateTime
} = require("../utils/userUtils");

// 获取未读消息数
router.get("/unreadCount", verifyToken, (req, res) => {
  // SQL查询:计算指定用户的未读消息数
  const sql = `
    SELECT COUNT(*) AS unreadCount
    FROM messages
    WHERE receiver_id = ? AND is_read = 0
  `;

  // 执行SQL查询,使用用户ID作为参数
  sqlconfig.query(sql, [req.user.userId], (err, result) => {
    if (err) {
      // 如果查询出错,返回服务器错误响应
      return createResponse(res, "SERVER_ERROR", null, err.toString());
    }
    // 返回成功响应,包含未读消息数
    createResponse(
      res,
      "SUCCESS", {
        unreadCount: result[0].unreadCount,
      },
      "获取未读消息数成功"
    );
  });
});

// 获取客服消息列表
router.get("/list", verifyToken, (req, res) => {
  // SQL查询:获取与当前用户相关的所有对话列表
  const sql = `
    SELECT 
      c.conversation_id,
      c.initiator_id AS userId,
      u.user_name AS userName,
      c.last_message AS lastMessage,
      c.updated_at AS timestamp,
      (SELECT COUNT(*) 
       FROM messages m 
       WHERE m.conversation_id = c.conversation_id 
         AND m.is_read = 0 
         AND m.receiver_id = ?) AS unreadCount
    FROM 
      conversations c
    JOIN
      users u ON c.initiator_id = u.user_id
    WHERE 
      c.initiator_id != ?
    ORDER BY 
      c.updated_at DESC
  `;

  // 执行SQL查询,使用用户ID作为参数
  sqlconfig.query(sql, [req.user.userId, req.user.userId], (err, result) => {
    if (err) {
      console.error("SQL Error:", err);
      return createResponse(res, "SERVER_ERROR", null, "数据库查询错误");
    }

    // 格式化结果中的时间戳
    const formattedResult = result.map((item) => ({
      ...item,
      timestamp: formatDateTime(item.timestamp),
    }));

    // 返回成功响应,包含格式化后的对话列表
    createResponse(res, "SUCCESS", formattedResult, "获取客服消息列表成功");
  });
});

// CMS后台获取聊天历史
router.get("/chatHistory/:conversationId", verifyToken, (req, res) => {
  const {
    conversationId
  } = req.params;

  // SQL查询:获取指定对话的所有消息历史
  const sql = `
    SELECT m.id, m.conversation_id, m.sender_id, m.receiver_id, m.content, m.timestamp, 
           m.sender_role, m.receiver_role, m.is_read,
           COALESCE(s.nick_name, s.user_name) AS senderNickName,
           COALESCE(r.nick_name, r.user_name) AS receiverNickName
    FROM messages m
    LEFT JOIN users s ON m.sender_id = s.user_id
    LEFT JOIN users r ON m.receiver_id = r.user_id
    WHERE m.conversation_id = ?
    ORDER BY m.timestamp ASC
  `;

  // 执行SQL查询,使用对话ID作为参数
  sqlconfig.query(sql, [conversationId], (err, result) => {
    if (err) {
      console.error("Error fetching chat history:", err);
      return createResponse(res, "SERVER_ERROR", null, "获取聊天历史失败");
    }

    // 格式化查询结果
    const formattedResult = result.map((message) => ({
      id: message.id,
      conversationId: message.conversation_id,
      senderId: message.sender_id,
      receiverId: message.receiver_id,
      content: message.content,
      timestamp: formatDateTime(message.timestamp),
      senderRole: message.sender_role,
      receiverRole: message.receiver_role,
      isRead: message.is_read,
      senderNickName: message.senderNickName,
      receiverNickName: message.receiverNickName,
    }));

    // 获取所有未读消息的ID
    const unreadMessageIds = result
      .filter((message) => message.is_read === 0)
      .map((message) => message.id);

    if (unreadMessageIds.length > 0) {
      // 如果有未读消息,更新这些消息为已读状态
      const updateSql = `
        UPDATE messages 
        SET is_read = 1 
        WHERE id IN (?)
      `;

      sqlconfig.query(updateSql, [unreadMessageIds], (updateErr) => {
        if (updateErr) {
          console.error("Error updating messages to read:", updateErr);
          return createResponse(
            res,
            "SERVER_ERROR",
            null,
            "标记消息为已读失败"
          );
        }

        // 返回成功响应,包含格式化后的聊天历史
        createResponse(res, "SUCCESS", formattedResult, "获取聊天历史成功");
      });
    } else {
      // 如果没有未读消息,直接返回成功响应
      createResponse(res, "SUCCESS", formattedResult, "获取聊天历史成功");
    }
  });
});

// C端前台获取聊天记录
router.get("/getChatHistory", verifyToken, (req, res) => {
  const userId = req.user.userId;

  // SQL查询:获取用户的所有对话ID
  const conversationSql = `
    SELECT conversation_id 
    FROM conversations 
    WHERE initiator_id = ?
  `;

  // 执行SQL查询,使用用户ID作为参数
  sqlconfig.query(conversationSql, [userId], (err, conversations) => {
    if (err) {
      console.error("Error fetching conversations:", err);
      return createResponse(res, "SERVER_ERROR", null, "获取对话列表失败");
    }

    if (conversations.length === 0) {
      return createResponse(res, "SUCCESS", [], "无对话记录");
    }

    // 提取所有对话ID
    const conversationIds = conversations.map((conv) => conv.conversation_id);

    // SQL查询:获取指定对话的所有消息
    const messageSql = `
      SELECT m.id, m.conversation_id, m.sender_id, m.receiver_id, m.content, m.timestamp, 
             m.sender_role, m.receiver_role,
             COALESCE(s.nick_name, s.user_name) AS senderNickName,
             COALESCE(r.nick_name, r.user_name) AS receiverNickName
      FROM messages m
      LEFT JOIN users s ON m.sender_id = s.user_id
      LEFT JOIN users r ON m.receiver_id = r.user_id
      WHERE m.conversation_id IN (?)
      ORDER BY m.timestamp ASC
    `;

    // 执行SQL查询,使用对话ID数组作为参数
    sqlconfig.query(messageSql, [conversationIds], (err, messages) => {
      if (err) {
        console.error("Error fetching messages:", err);
        return createResponse(res, "SERVER_ERROR", null, "获取聊天记录失败");
      }

      // 格式化消息数据
      const formattedMessages = messages.map((message) => ({
        id: message.id,
        conversationId: message.conversation_id,
        senderId: message.sender_id,
        receiverId: message.receiver_id,
        content: message.content,
        timestamp: formatDateTime(message.timestamp),
        senderRole: message.sender_role,
        receiverRole: message.receiver_role,
        senderNickName: message.senderNickName,
        receiverNickName: message.receiverNickName,
      }));

      // 返回成功响应,包含格式化后的聊天记录
      createResponse(res, "SUCCESS", formattedMessages, "获取聊天记录成功");
    });
  });
});

// 发送消息
router.post("/sendMessage", verifyToken, (req, res) => {
  const {
    conversationId,
    content
  } = req.body;
  const sender_id = req.user.userId;

  // 检查消息内容是否为空
  if (!content) {
    return createResponse(res, "BAD_REQUEST", null, "消息内容不能为空");
  }

  // SQL查询:获取用户角色
  const userRoleQuery = "SELECT role FROM users WHERE user_id = ?";
  sqlconfig.query(userRoleQuery, [sender_id], (roleErr, roleResult) => {
    if (roleErr) {
      console.error("Error querying user role:", roleErr);
      return createResponse(res, "SERVER_ERROR", null, "查询用户角色失败");
    }

    if (roleResult.length === 0) {
      return createResponse(res, "NOT_FOUND", null, "未找到用户信息");
    }

    // 确定发送者和接收者的角色
    const isAdmin = roleResult[0].role === "ADMIN";
    const senderRole = isAdmin ? "ADMIN" : "USER";
    const receiverRole = isAdmin ? "USER" : "ADMIN";
    let senderNickName = ''
    // SQL查询:检查会话是否存在
    const checkConvQuery =
      "SELECT initiator_id FROM conversations WHERE conversation_id = ?";
    sqlconfig.query(
      checkConvQuery,
      [conversationId],
      (checkErr, checkResult) => {
        if (checkErr) {
          console.error("Error checking conversation:", checkErr);
          return createResponse(res, "SERVER_ERROR", null, "查询会话失败");
        }

        if (checkResult.length === 0) {
          // 会话不存在,创建新会话
          const createConvQuery = `
          INSERT INTO conversations (conversation_id, initiator_id, first_message, last_message, created_at, updated_at)
          VALUES (?, ?, ?, ?, NOW(), NOW())
        `;
          sqlconfig.query(
            createConvQuery,
            [conversationId, sender_id, content, content],
            (createErr) => {
              if (createErr) {
                console.error("Error creating conversation:", createErr);
                return createResponse(
                  res,
                  "SERVER_ERROR",
                  null,
                  "创建会话失败"
                );
              }
              getReceiverIdAndInsertMessage(isAdmin, sender_id);
            }
          );
        } else {
          // 会话存在,更新会话
          const updateConvQuery = `
          UPDATE conversations 
          SET last_message = ?, updated_at = NOW() 
          WHERE conversation_id = ?
        `;
          sqlconfig.query(
            updateConvQuery,
            [content, conversationId],
            (updateErr) => {
              if (updateErr) {
                console.error("Error updating conversation:", updateErr);
                return createResponse(
                  res,
                  "SERVER_ERROR",
                  null,
                  "更新会话失败"
                );
              }
              getReceiverIdAndInsertMessage(
                isAdmin,
                checkResult[0].initiator_id
              );
            }
          );
        }
      }
    );

    // 获取接收者ID并插入消息
    function getReceiverIdAndInsertMessage(isAdmin, initiatorId) {
      if (isAdmin) {
        insertMessage(initiatorId);
      } else {
        getAdminId((adminId) => {
          if (adminId) {
            insertMessage(adminId);
          } else {
            createResponse(res, "SERVER_ERROR", null, "无法获取管理员ID");
          }
        });
      }
    }

    // 插入新消息
    function insertMessage(receiver_id) {
      const insertSql = `
        INSERT INTO messages (conversation_id, sender_id, receiver_id, content, timestamp, is_read, sender_role, receiver_role)
        VALUES (?, ?, ?, ?, NOW(), 0, ?, ?)
      `;
      sqlconfig.query(
        insertSql,
        [
          conversationId,
          sender_id,
          receiver_id,
          content,
          senderRole,
          receiverRole,
        ],
        (insertErr, insertResult) => {
          if (insertErr) {
            console.error("Error sending message:", insertErr);
            return createResponse(res, "SERVER_ERROR", null, "发送消息失败");
          }
          // 查询用户名
          const sql = `
          SELECT 
              u.user_id,
              u.user_name,
              u.nick_name,
              u.role,
              'sender' AS user_type
          FROM 
              users u
          WHERE 
              u.user_id = ?
          `;

          sqlconfig.query(
            sql,
            [sender_id],
            (err, results) => {
              if (err) {
                console.error("Error querying users:", err);
                return;
              }
              const data = results[0]
              senderNickName = data.nick_name ? data.nick_name : data.user_name
              // 构造消息对象
              const message = {
                id: insertResult.insertId,
                conversationId: conversationId,
                sender: sender_id,
                receiver: receiver_id,
                content,
                timestamp: new Date().toISOString(),
                senderRole,
                receiverRole,
                senderNickName
              };

              // 使用WebSocket发送消息
              if (isAdmin) {
                sendToUser(receiver_id, message);
              } else {
                sendToAdmins(message);
              }

              // 返回成功响应
              createResponse(
                res,
                "SUCCESS", {
                  messageId: insertResult.insertId,
                  conversationId,
                },
                "消息发送成功"
              );
            }
          );


        }
      );
    }
  });
});

// 获取管理员ID
function getAdminId(callback) {
  // SQL查询:获取一个管理员用户的ID
  const adminQuery = "SELECT user_id FROM users WHERE role = 'ADMIN' LIMIT 1";
  sqlconfig.query(adminQuery, (err, results) => {
    if (err) {
      console.error("Error fetching admin ID:", err);
      callback(null);
    } else if (results.length > 0) {
      callback(results[0].user_id);
    } else {
      console.error("No admin user found");
      callback(null);
    }
  });
}

// 标记消息为已读
router.put("/markAsRead/:conversationId", verifyToken, (req, res) => {
  const {
    conversationId
  } = req.params;
  // SQL查询:将指定对话中的未读消息标记为已读
  const sql = `
    UPDATE messages
    SET is_read = 1
    WHERE conversation_id = ? AND receiver_id = ? AND is_read = 0
  `;

  // 执行SQL查询,使用对话ID和用户ID作为参数
  sqlconfig.query(sql, [conversationId, req.user.userId], (err, result) => {
    if (err) {
      // 如果更新操作出错,返回服务器错误响应
      return createResponse(res, "SERVER_ERROR", null, err.toString());
    }
    // 返回成功响应,包含受影响的行数
    createResponse(
      res,
      "SUCCESS", {
        affectedRows: result.affectedRows,
      },
      "消息已标记为已读"
    );
  });
});

// 导出路由模块
module.exports = router;